#!/usr/bin/env bash

# DEBUGLOG=true
function Replace()
{
    local level=0
    local replaced_text=""
    local target_text=""
    local this_have=false
    local last_have=false
    local args=""
    local flag=""
    while read line; do
        debuglog
        debuglog "readline: '$line'"

        if [ "$line" != "" ]; then
            this_have=true
        else
            this_have=false
        fi

        if [ "$level" == "0" ]; then
            replaced_text="$(sed -e 's@^[^<]*<@@' -e 's@>$@@' -e "s@'@'\"'\"'@g" <<< "$line")"
            debuglog "replaced_text: '$replaced_text'"
        elif [ "$level" == "1" ]; then
            target_text="$(sed -e 's@^[^<]*<@@' -e 's@>$@@' -e "s@'@'\"'\"'@g" <<< "$line")"
            debuglog "target_text: '$target_text'"
        elif [ "$level" == "2" ] && $this_have; then
            flag="$(sed -e 's@^[^:]*:@@' <<< "$line")"
            debuglog "flag: '$flag'"
        fi

        if ! $this_have && $last_have && (( level >= 1 )); then
            args+=" -e 's@$replaced_text@$target_text@$flag'"
            debuglog "args: +'s@$replaced_text@$target_text@$flag'\n"
        fi

        if [ "$line" != "" ]; then
            last_have=true
            ((level++))
        else
            last_have=false
            level=0; flag=""
        fi
        debuglog "last_have=$last_have"
    done <<< "$1"

    eval sed -u $args
}
